package top.infopub.util;


import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import top.infopub.cache.RedisCached;


/**
 * 定时过期Redis工具类
 * @author Awoke
 * @version 2019年1月22日
 * @see RedisExpiresUtil
 * @since
 */
@Component
public class RedisExpiresUtil {

    private static final Logger log = LoggerFactory.getLogger(RedisExpiresUtil.class);

    /** zset key，存储需要定时清理的key  **/
    public static final String COMMON_TIME_EXPIRES_ZSET = "common:time.expires:zset";

    /** hash key和 map key的拼接串  **/
    public static final String HASH_JOIN_MAP_CHAR = "~";

    @Autowired
    private RedisCached redisCached;

    /**
     * 存储定时过期key(key= hashkey+'~'+mapkey)到 zset，并保存对应数据到hash
     * @param hashkey   Hash对应key
     * @param mapkey   Hash内mapkey
     * @param value  Hash内value
     * @param msec   保留时长（单位：毫秒）
     * @return 
     * @since 
     * @see
     */
    public boolean zaddAndHset(String hashkey, String mapkey, Object value, long msec) {
        try {
            redisCached.zadd(COMMON_TIME_EXPIRES_ZSET, System.currentTimeMillis() + msec,
                hashkey + HASH_JOIN_MAP_CHAR + mapkey);
            redisCached.updateHashCached(hashkey, mapkey, value);
            return true;
        }
        catch (Exception e) {
            log.error("", e);
            return false;
        }
    }

    /**
     * 存储定时过期key(key= hashkey+'~'+mapkey)到 zset，并保存对应数据到hash
     * @param hashkey   Hash对应key
     * @param mapkey   Hash内mapkey
     * @param value  Hash内value
     * @param msec   保留时长（单位：毫秒）
     * @return 
     * @since 
     * @see
     */
    public boolean zaddAndHsetLong(String hashkey, String mapkey, long value, long msec) {
        try {
            redisCached.zadd(COMMON_TIME_EXPIRES_ZSET, System.currentTimeMillis() + msec,
                hashkey + HASH_JOIN_MAP_CHAR + mapkey);
            redisCached.hsetLong(hashkey, mapkey, value);
            return true;
        }
        catch (Exception e) {
            log.error("", e);
            return false;
        }
    }

    /**
     * 从zset中删除定时过期Key(key= hashkey+'~'+mapkey)，并删除hash中对应数据
     * @param hashkey   Hash对应key
     * @param mapkey   Hash内mapkey
     * @return 
     * @since 
     * @see
     */
    public boolean delete(String hashkey, String mapkey) {
        String key = hashkey + HASH_JOIN_MAP_CHAR + mapkey;
        try {
            // 删除定时Set
            redisCached.zrem(COMMON_TIME_EXPIRES_ZSET, key);
            // 删除Hash中的键值对
            redisCached.deleteHashCached(hashkey, mapkey);
            return true;
        }
        catch (Exception e) {
            log.error("occur error,hashkey=" + hashkey + ",mapkey=" + mapkey, e);
            return false;
        }
    }
}
